package com.winhxd.b2c.customer.service.impl;

import com.winhxd.b2c.common.cache.Cache;
import com.winhxd.b2c.common.constant.BusinessCode;
import com.winhxd.b2c.common.constant.CacheName;
import com.winhxd.b2c.common.domain.ResponseResult;
import com.winhxd.b2c.common.domain.customer.condition.MiniProgramSharePicCondition;
import com.winhxd.b2c.common.domain.customer.condition.MiniProgramStoreSharePicCondition;
import com.winhxd.b2c.common.feign.message.MessageServiceClient;
import com.winhxd.b2c.common.oss.OSSFileUtil;
import com.winhxd.b2c.common.util.JsonUtil;
import com.winhxd.b2c.customer.service.GraphicsGenerateService;
import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

/**
 * @author shumin
 * @create 2019/1/12 0012 15:42
 */
@Service
public class GraphicsGenerateImpl implements GraphicsGenerateService {
    private Logger logger = LoggerFactory.getLogger(GraphicsGenerateImpl.class);

    private final String moduleName = "图片生成service";
    //******************************************生成小程序中商品详情的分享图片->图片固定参数************************
    //图片的宽度
    final int imageWidth = 450;
    //图片的高度
    final int imageHeight = 674;
    //(第 1 行)图片属性
    final int line3_x = 0;
    final int line3_y = 0;
    final int lin3_img_width = imageWidth;
    final int lin3_img_high = 390;
    //第 2 行文字的属性,商品名称
    final int line1_x = 30;
    final int line1_y = 434;
    final String line1_font_name = "微软雅黑";
    final int line1_font_size = 28;
    //第 3 行文字的属性,货号和颜色
    final int line2_x = 30;
    final int line2_y = 481;
    final String line2_font_name = "黑体";
    final int line2_font_size = 24;
    //第 4 行 左侧文字属性,价格
    final int line4_left_x = 30;
    final int line4_left_y = 540;
    final String line4_left_font_name = "宋体";
    final int line4_left_font_size = 32;
    //第 4 行 右侧图片属性, 小程序码
    final int line4_right_x = 320;
    final int line4_right_y = 405;
    final int line4_right_img_width = 105;
    final int line4_right_img_high = 105;
    //第 5 行 左侧微信头像属性 + 微信昵称属性
    final int line5_left_x = 30;
    final int line5_left_y = 580;
    final int line5_left_img_width = 50;
    final int line5_left_img_high = 50;
    final String line5_left_font_name = "黑体";
    final int line5_left_font_size = 24;
    final int img_size = 134;
    //第 5 行 右侧文字属性
    final int line5_right_x = 325;
    final int line5_right_y = 530;
    final String line5_right_font_name = "宋体";
    final int line5_right_font_size = 15;
    final int max_cache_time = 60 * 60 * 24 * 30;
    //******************************************生成小程序中商品详情的分享图片->图片固定参数************************
    //@Value("${wechat.wxacodeUrl}")
    private String wxacodeUrl= "https://api.weixin.qq.com/wxa/getwxacodeunlimit";
    @Value("${upload.oss.bucketname}")
    private String bucketName = "hxd-outlet";
    @Resource
    private Cache cache;
    @Resource
    private MessageServiceClient messageServiceClient;

    /**
     *生成小程序中商品详情的分享图片
     * @param condition 条件
     * @return
     */
    @Override
    public String generateMiniProgramProductSharePic(MiniProgramSharePicCondition condition) {
        logger.info("{} - 生成小程序商品详情的分享图片 - 参数 {}", moduleName, condition.toString());
        //需要做缓存,如果缓存有,则取缓存,否则,重新生成
        String result = getProductSharePicByCache(condition);
        if(StringUtils.isNotBlank(result)){
            logger.info("{} - 生成小程序商品详情的分享图片- 从缓存中读取成功 - 图片地址", moduleName, result);
            return result;
        }
        //设置图片的大小,以及颜色标准
        BufferedImage image = new BufferedImage(imageWidth, imageHeight, BufferedImage.TYPE_INT_RGB);
        //设置图片的背景色
        Graphics2D main = image.createGraphics();
        //图片背景色
        main.setColor(Color.white);
        //背景色大小
        main.fillRect(0, 0, imageWidth, imageHeight);

        //***********************页面头部 商品图片部分
        Graphics mainPic = image.getGraphics();
        BufferedImage bimg = null;
        try {
            URL url = new URL(condition.getSpuImageUrl());
            bimg = ImageIO.read(url);
        } catch (Exception e) {

        }
        if(bimg!=null){
            mainPic.drawImage(bimg, line3_x, line3_y, lin3_img_width, lin3_img_high, null);
        }
        //***********************页面头部 商品名称 + 商品编码 + 颜色
        Graphics2D title = image.createGraphics();
        //设置字体颜色，先设置颜色，再填充内容
        title.setColor(Color.BLACK);
        title.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        // 第 1 行 商品名称
        //设置字体
        Font titleFont = new Font(line1_font_name, Font.PLAIN, line1_font_size);
        title.setFont(titleFont);
        //x,y为文字开始位置的坐标
        //把商品名称字数做限制,超过12个字的,用 ... 代替
        String tmpName = condition.getSkuName();
        int maxLenth = 9;
        if(condition.getSkuName().length() > maxLenth){
            tmpName = condition.getSkuName().substring(0, maxLenth) + "...";
        }
        title.drawString(tmpName, line1_x, line1_y);
        //第 2 行 商品编号 + 颜色
        titleFont = new Font(line2_font_name, Font.PLAIN, line2_font_size);
        title.setFont(titleFont);
        title.setColor(Color.gray);
        title.drawString(condition.getSkuStyleCode(), line2_x, line2_y);
        title.drawString(condition.getColorAttributeOptionValue(), line2_x + 186, line2_y);

        //***********************页面下部 价格 + 微信信息 + 小程序码
        //第 4 行左侧 价格
        titleFont = new Font(line4_left_font_name, Font.PLAIN, 20);
        title.setFont(titleFont);
        title.setColor(Color.red);
        title.drawString("¥", line4_left_x , line4_left_y - 2);
        titleFont = new Font(line2_font_name, Font.BOLD, line4_left_font_size);
        title.setFont(titleFont);
        title.setColor(Color.red);
        title.drawString(String.valueOf(condition.getSalePrice()), line4_left_x + 10, line4_left_y);
        //第 4 行右侧 小程序码
        mainPic = image.getGraphics();
        bimg = null;
        try {
            ResponseResult<String> accessToken = messageServiceClient.getAccessToken();
            if(accessToken.getCode() == BusinessCode.CODE_OK){
                InputStream inputStream = gainMiniProgramCode(accessToken.getData(), condition.getScene(), condition.getPage(), 50);
                bimg = ImageIO.read(inputStream);
                if(bimg == null){
                    logger.info("{} - 生成小程序商品详情的分享图片- 小程序码生成失败", moduleName);
                }else{
                    logger.info("{} - 生成小程序商品详情的分享图片- 小程序码生成成功", moduleName);
                }
            }
            //bimg = ImageIO.read(new URL("https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1547444916&di=c8042a59b920a8ba885d12e94934787d&src=http://pic.qqtn.com/up/2018-3/2018032307574186060.png"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("{} - 生成小程序商品详情的分享图片- 小程序码生成失败", moduleName);
        }
        if(bimg!=null){
            mainPic.drawImage(bimg, line4_right_x, line4_right_y, line4_right_img_width, line4_right_img_high, null);
            mainPic.dispose();
        }
        //第 5 行左侧 微信头像图片 + 微信昵称
        mainPic = image.getGraphics();
        bimg = null;
        try {
            if(StringUtils.isNotBlank(condition.getWechatHeadImg())){
                URL url = new URL(condition.getWechatHeadImg());
                bimg = ImageIO.read(url);
                BufferedImage tag = new BufferedImage(img_size, img_size, BufferedImage.TYPE_INT_RGB);
                tag.getGraphics().drawImage(bimg, 0, 0,img_size, img_size, null);
                bimg = roundImage(tag, img_size, img_size);
                logger.info("{} - 生成小程序商品详情的分享图片- 用户头像处理成功", moduleName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("{} - 生成小程序商品详情的分享图片- 用户头像处理失败", moduleName);
        }
        if(bimg!=null){
            mainPic.drawImage(bimg, line5_left_x, line5_left_y, line5_left_img_width, line5_left_img_high, null);
            mainPic.dispose();
        }
        titleFont = new Font(line5_left_font_name, Font.PLAIN, line5_left_font_size);
        title.setFont(titleFont);
        title.setColor(Color.gray);
        title.drawString(condition.getWechatName(), line5_left_x + 53, line5_left_y + 35);
        //第 5 行右侧 小程序文案
        titleFont = new Font(line2_font_name, Font.PLAIN, line5_right_font_size);
        title.setFont(titleFont);
        title.setColor(Color.gray);
        title.drawString("识别小程序码", line5_right_x, line5_right_y);
        try {
        image = setRadius(image,10, 0, 0);

        }catch (Exception e){
            e.printStackTrace();
        }
        //生成文件名称
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
        String imgUrl = "";
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
            ImageIO.write(image, "png", imageOutput);
            InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            OSSFileUtil.uploadFile2OSS(bucketName, "prodShare/" + fileName, byteArrayOutputStream.toByteArray());
            imgUrl = OSSFileUtil.getFileUrl(bucketName, "prodShare/" +fileName);
            logger.info("{} - 生成小程序商品详情的分享图片- 图片生成并上传成功 - 图片地址{}", moduleName, imgUrl);
//            createImage("e:/file/a.jpg", image);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("{} - 生成小程序商品详情的分享图片- 图片生成成功,上传失败", moduleName);
        }
        //存入缓存
//        String key = CacheName.CACHE_KEY_PRODUCT_SHARE +condition.getSkuName() + condition.getColorAttributeOptionValue() + condition.getSalePrice() + condition.getCustomerId();
//        cache.setex(key,  max_cache_time, imgUrl);
        logger.info("{} - 生成小程序商品详情的分享图片- 图片已经生成! - 图片地址{}", moduleName, imgUrl);
        return imgUrl;

    }
    /**
     * 图片设置圆角
     * @param srcImage
     * @param radius
     * @param border
     * @param padding
     * @return
     * @throws IOException
     */
    public static BufferedImage setRadius(BufferedImage srcImage, int radius, int border, int padding) throws IOException{
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        int canvasWidth = width + padding * 2;
        int canvasHeight = height + padding * 2;

        BufferedImage image = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gs = image.createGraphics();
        gs.setComposite(AlphaComposite.Src);
        gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gs.setColor(Color.WHITE);
        gs.fill(new RoundRectangle2D.Float(0, 0, canvasWidth, canvasHeight, radius, radius));
        gs.setComposite(AlphaComposite.SrcAtop);
        gs.drawImage(setClip(srcImage, radius), padding, padding, null);
        if(border !=0){
            gs.setColor(Color.GRAY);
            gs.setStroke(new BasicStroke(border));
            gs.drawRoundRect(padding, padding, canvasWidth - 2 * padding, canvasHeight - 2 * padding, radius, radius);
        }
        gs.dispose();
        return image;
    }
    /**
     * 图片切圆角
     * @param srcImage
     * @param radius
     * @return
     */
    public static BufferedImage setClip(BufferedImage srcImage, int radius){
        int width = srcImage.getWidth();
        int height = srcImage.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D gs = image.createGraphics();

        gs.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        gs.setClip(new RoundRectangle2D.Double(0, 0, width, height, radius, radius));
        gs.drawImage(srcImage, 0, 0, null);
        gs.dispose();
        return image;
    }
    /**
     * 从缓存中获取图片地址,如果缓存有,则取缓存,否则,重新生成
     * @param condition
     * @return
     */
    private String getProductSharePicByCache(MiniProgramSharePicCondition condition) {
        String key = CacheName.CACHE_KEY_PRODUCT_SHARE +condition.getSkuStyleCode() + condition.getColorAttributeOptionValue() + condition.getSalePrice() + condition.getCustomerId();
        return cache.get(key);
    }

    /**
     *  图片圆角转换,为一个矩形的图片生成圆角
     * @param image         需要转换的图片流
     * @param targetSize   目标边长
     * @param cornerRadius 目标圆的半径, 当它等于 targetSize 时, 就是圆形.
     * @return
     */
    private static BufferedImage roundImage(BufferedImage image, int targetSize, int cornerRadius) {
        BufferedImage outputImage = new BufferedImage(targetSize, targetSize, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = outputImage.createGraphics();
        g2.setComposite(AlphaComposite.Src);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.WHITE);
        g2.fill(new RoundRectangle2D.Float(0, 0, targetSize, targetSize, cornerRadius, cornerRadius));
        g2.setComposite(AlphaComposite.SrcAtop);
        g2.drawImage(image, 0, 0, null);
        g2.dispose();
        return outputImage;
    }

    /**
     *  将图片生成到磁盘
     * @param fileLocation
     */
    @SuppressWarnings("restriction")
    public void createImage(String fileLocation, BufferedImage image) {
        BufferedOutputStream bos = null;
        if(image != null){
            try {
                FileOutputStream fos = new FileOutputStream(fileLocation);
                bos = new BufferedOutputStream(fos);
                ImageIO.write(image, "jpeg", bos);
                bos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                if(bos!=null){//关闭输出流
                    try {
                        bos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 生成小程序码,并返回一个流
     * @param accessToken   调用凭证
     * @param scene          参数
     * @param page           扫描后,要跳转的页面
     * @param width          生成码的尺寸
     * @return
     * @throws IOException
     */
    private InputStream gainMiniProgramCode(String accessToken, String scene, String page, Integer width) throws IOException {
        try {
            URL url = new URL(wxacodeUrl + "?access_token=" + accessToken);
            logger.info("生成小程序商品详情的分享图片- 生成小程序码参数scene={},page={},width={},accessToken={},url={}", scene, page, width, accessToken, url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
            paramJson.put("scene", scene);
            paramJson.put("page", page);
            paramJson.put("width", width);
            paramJson.put("auto_color", true);
            printWriter.write(paramJson.toString());
            // flush输出流的缓冲
            printWriter.flush();
            //开始获取数据
            InputStream is = httpURLConnection.getInputStream();
            return is;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 经销商分享图片生成
     * @author ghf
     * @Description
     * @date
     * @param
     * @return
     */
    @Override
    public String generateMiniProgramStoreSharePic(MiniProgramStoreSharePicCondition condition) {
        String result = "";
//        = this.getStoreSharePicByCache(condition);
//        if(StringUtils.isNotBlank(result)){
//            return result;
//        }
        // 头像宽度
        int headerWidth = 136;
        // 头像高度
        int headerHeight = 136;
        // 头像y轴坐标
        int headerY = 20;
        // 第一行文字
        String row1 = condition.getNickName();
        // 第一行文字的Y坐标
        int row1Y = 183;
        // 第二行文字
        String row2 = condition.getRow2();
        // 第二行文字的Y坐标
        int row2Y = 217;
        // 第三行文字
        String row3 = condition.getRow3();
        // 第三行文字的Y坐标
        int row3Y = 266;
        // 第四行文字
        String row4 = condition.getRow4();
        // 第四行文字的Y坐标
        int row4Y = 574;
        // 小程序码宽
        int miniProgramWidth = 246;
        // 小程序码高
        int miniProgramHeight = 246;
        // 小程序Y坐标
        int miniProgramY = 300;
        // 主图像宽
        int imageWidth = 450;
        // 主图像高
        int imageHeight = 600;
        logger.info("{} - 生成小程序商品详情的分享图片- 经销商分享图片生成 - 开始 - 参数={}", moduleName, JsonUtil.toJSONString(condition));
        BufferedImage image = new BufferedImage(imageWidth - 2, imageHeight, BufferedImage.TYPE_INT_RGB);
        try {
            URL mainUrl = new URL(condition.getBackground());
            BufferedImage temp = ImageIO.read(mainUrl);
            image.getGraphics().drawImage(temp, 0, 0,imageWidth, imageHeight, null);
            logger.info("{} - 生成小程序商品详情的分享图片- 背景图生成成功", moduleName);
        } catch (IOException e) {
            e.printStackTrace();

        }
        //设置图片的背景色
        Graphics2D main = image.createGraphics();
        // 抗锯齿
        main.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        //***********************插入头像
        Graphics mainPic = image.getGraphics();
        BufferedImage bimg = null;
        try {
            // 获取在线微信头像url
            URL url = new URL(condition.getNickImg());
            bimg = ImageIO.read(url);
            BufferedImage tag = new BufferedImage(headerWidth, headerHeight, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(bimg, 0, 0,headerWidth, headerHeight, null);
            bimg = roundImage(tag, headerWidth, headerHeight);
            logger.info("{} - 生成小程序商品详情的分享图片- 头像生成成功 - 准备写入", moduleName);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (bimg != null) {
            mainPic.drawImage(bimg, imageWidth / 2 - headerWidth / 2, headerY, headerWidth, headerHeight, null);
            mainPic.dispose();
            logger.info("{} - 生成小程序商品详情的分享图片- 头像写入成功", moduleName);
        }
        //***********************设置下面的提示框
        Graphics2D textArea = image.createGraphics();
        // 抗锯齿
        textArea.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // 1.一级分销商微信名称
        // 设置字体颜色，先设置颜色，再填充内容
        textArea.setColor(new Color(255,223,154));
        Font row1Font = new Font("宋体", Font.BOLD, 26);
        this.drawString(textArea, row1, row1Font, imageWidth, row1Y);
        logger.info("{} - 生成小程序商品详情的分享图片- 微信昵称写入成功", moduleName);

        // 2.邀请你成为原译商城店长
        textArea.setColor(new Color(0,50,79));
        Font row2Font = new Font("宋体", Font.BOLD, 26);
        this.drawString(textArea, row2, row2Font, imageWidth, row2Y);
        logger.info("{} - 生成小程序商品详情的分享图片- 第二行文字写入成功", moduleName);

        // 3.带货赚收益，网红就是你
        textArea.setColor(new Color(78,70,58));
        Font row3Font = new Font("黑体", Font.BOLD, 32);
        this.drawString(textArea, row3, row3Font, imageWidth, row3Y);
        logger.info("{} - 生成小程序商品详情的分享图片- 第三行文字写入成功", moduleName);

        //***********************设置下方二维码
        Graphics qrPic = image.getGraphics();
        BufferedImage qrimg = null;
        try {
            // 在线获取小程序二维码的流
            InputStream inputStream = gainMiniProgramCode(condition.getAccessToken(), condition.getScene(), condition.getPage(), 50);
            qrimg = ImageIO.read(inputStream);
            BufferedImage tag = new BufferedImage(miniProgramWidth, miniProgramHeight, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(qrimg, 0, 0, miniProgramWidth, miniProgramHeight, null);
            qrimg = roundImage(tag, miniProgramWidth, miniProgramHeight);
            logger.info("{} - 生成小程序商品详情的分享图片- 小程序二维码生成成功", moduleName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (qrimg != null) {
            qrPic.drawImage(qrimg, imageWidth / 2 - miniProgramWidth / 2 , miniProgramY, miniProgramWidth, miniProgramHeight, null);
            qrPic.dispose();
            logger.info("{} - 生成小程序商品详情的分享图片- 小程序二维码写入成功", moduleName);
        }
        //***********************设置下方提示
        textArea.setColor(new Color(250,229,199));
        Font row4Font = new Font("宋体", Font.BOLD, 24);
        this.drawString(textArea, row4, row4Font, imageWidth, row4Y);
        logger.info("{} - 生成小程序商品详情的分享图片- 最下方提示扫描文字写入成功", moduleName);

        //生成文件名称
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".jpg";
        try {
//            createImage("c:\\"+ fileName +".jpg", image);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
            ImageIO.write(image, "png", imageOutput);
            OSSFileUtil.uploadFile2OSS(bucketName, "storeShare/" + fileName, byteArrayOutputStream.toByteArray());
            result = OSSFileUtil.getFileUrl(bucketName, "storeShare/" +fileName);
            logger.info("{} - 生成经销商分享图片- 图片生成并上传成功 - 图片地址{}", moduleName, result);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("{} - 生成经销商分享图片片- 图片生成成功,上传失败", moduleName);
        }
        //存入缓存
//        String key = CacheName.CACHE_KEY_STORE_SHARE + condition.getOpenid();
//        cache.setex(key,  max_cache_time, result);
        return result;
    }

    /**
     * 从缓存中获取图片地址,如果缓存有,则取缓存,否则,重新生成
     * @param condition
     * @return
     */
    private String getStoreSharePicByCache(MiniProgramStoreSharePicCondition condition) {
        String key = CacheName.CACHE_KEY_STORE_SHARE + condition.getOpenid();
        return cache.get(key);
    }
    /**
     * @author genghaifei
     * @Description 将文字绘制到图片中
     * @date
     * @param
     * @return
     */
    private void drawString(Graphics2D textArea, String rowName, Font rowFont, int imageWidth, int rowY){
        // 设置子图
        textArea.setFont(rowFont);
        // 计算文字长度，计算居中的x点坐标
        FontMetrics fm = textArea.getFontMetrics(rowFont);
        int rowTextWidth = fm.stringWidth(rowName);
        int rowX = (imageWidth - rowTextWidth) / 2;
        // 表示这段文字在图片上的位置(x,y) .第一个是你设置的内容。
        textArea.drawString(rowName, rowX, rowY);
    }

    public static void main(String[] args) {
        System.out.println("¥");
    }
}
